#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "message_queue.h"

typedef struct _node {
    char token[128];
    char owner[128];
    char repo[128];
    char branch[128];
    char branch_hash[128];
    struct _node *next;
}node;

// 队列采用尾插法，只需要记录队尾即可
typedef struct queue{
    node *data;
    node *rear;
}message_queue;

static message_queue head;

void queue_compile_init() {
    head.data = (node *)malloc(sizeof(node));
    head.data->next = NULL;
    head.rear = head.data;
}

int queue_compile_add(const char *token, const char *owner, const char *repo, const char *branch, const char *branch_hash) {
    node *temp = (node *)malloc(sizeof(node));

    if(token == NULL || owner == NULL || repo == NULL || branch == NULL || branch_hash == NULL) {
        if(temp != NULL) {
            free(temp);
        }
        return QUEUE_ERR_BAD_INPUT;
    }

    strncpy(temp->token, token, sizeof(temp->token));
    strncpy(temp->owner, owner, sizeof(temp->owner));
    strncpy(temp->repo, repo, sizeof(temp->repo));
    strncpy(temp->branch, branch, sizeof(temp->branch));
    strncpy(temp->branch_hash, branch_hash, sizeof(temp->branch_hash));

    temp->next = NULL;

    head.rear->next = temp;
    head.rear = temp;

    return QUEUE_OK;
}

int queue_compile_get(char token[128], char owner[128], char repo[128], char branch[128], char branch_hash[128]) {
    node * temp = head.data->next;

    if(token == NULL || owner == NULL || repo == NULL || branch == NULL || branch_hash == NULL) {
        return QUEUE_ERR_BAD_INPUT;
    }

    if(temp == NULL) {
        return QUEUE_STATUS_EMPTY;
    }

    if(temp == head.rear) {
        head.rear = head.data;
    }
    head.data->next = temp->next;

    strncpy(token, temp->token, sizeof(temp->token));
    strncpy(owner, temp->owner, sizeof(temp->owner));
    strncpy(repo, temp->repo, sizeof(temp->repo));
    strncpy(branch, temp->branch, sizeof(temp->branch));
    strncpy(branch_hash, temp->branch_hash, sizeof(temp->branch_hash));

    free(temp);

    return QUEUE_OK;
}

void debug_queue() {
    node *temp = head.data->next;
    while(temp != NULL) {
        printf("%s %s %s %s\n", temp->branch, temp->owner, temp->repo, temp->token);
        temp = temp->next;
    }
}

void debug_queue_compile_free() {
    node *temp = head.data;
    node *tempfree = NULL;
    while(temp != NULL) {
        tempfree = temp;
        temp = temp->next;
        free(tempfree);
    }
}